package com.rent.wechat.gateway.config;

import com.alibaba.fastjson.JSONArray;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author zhang
 * @create 2022/4/15 11:22
 */
@Slf4j
@Primary
@Component
@RequiredArgsConstructor
public class SwaggerResourceProvider implements SwaggerResourcesProvider {

    /**
     * swagger2默认的url后缀
     */
    private static final String SWAGGER2_URL = "/v2/api-docs";

    private static final String SWAGGER_RESOURCE = "/swagger-resources";
    /**
     * 路由定位器
     */
    private final RouteLocator routeLocator;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String gatewayName;

    @Autowired
    private RestTemplate restTemplate;


    @Override
    public List<SwaggerResource> get() {
        // 路由
        Set<Route> routes = new HashSet<>();
        // 1. 获取路由Uri 中的Host=> 服务注册则为服务名=》app-service001
        routeLocator.getRoutes()
                .filter(route -> route.getUri().getHost() != null)
                .filter(route -> !gatewayName.equals(route.getUri().getHost()))
                .subscribe(routes::add);
        // 资源
        List<SwaggerResource> resources = new ArrayList<>();
        // 2. 创建自定义资源
        for (Route route : routes) {
            String host = route.getUri().getHost();
            String name = (String) route.getMetadata().get("name");
            if (name == null || name.isEmpty()) continue;
            boolean isHas = false;
            for (SwaggerResource resource : resources) {
                if (resource.getName().equals(name)) {
                    isHas = true;
                    break;
                }
            }
            if (isHas) continue;
            log.info("添加路由:" + host + "--" + name);
            try {
                JSONArray list = restTemplate.getForObject("http://" + host + SWAGGER_RESOURCE, JSONArray.class);
                log.info("访问路由:{}", list);
            } catch (Exception e) {
                log.info("访问路由失败:{}", e.getMessage());
                if (e.getMessage() != null && !e.getMessage().contains("401")) continue;
            }
            String serviceUrl = "/" + host + SWAGGER2_URL; // 后台访问添加服务名前缀
            log.info("添加服务{}", serviceUrl);
            SwaggerResource swaggerResource = new SwaggerResource(); // 创建Swagger 资源
            swaggerResource.setUrl(serviceUrl); // 设置访问地址
            swaggerResource.setName(name); // 设置名称
            swaggerResource.setSwaggerVersion("1.0.0");
            resources.add(swaggerResource);
        }
        return resources;
    }

}
